package com.accum.client.presenter;

import java.util.List;

import com.accum.client.GreetingServiceAsync;
import com.accum.shared.pojo.WordEntry;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class WordListPresenter implements Presenter {
	
	public interface Display{
		 Widget asWidget();
		 HasClickHandlers getAddButton();
		 String getEntryName();
		 void clearEntryName();
		 void setData(List<WordEntry> data);
		void addToList(WordEntry result);
	}
	
	private final GreetingServiceAsync rpcService;
	private final HandlerManager eventBus;
	private final Display display;

	public WordListPresenter(GreetingServiceAsync rpcService, HandlerManager eventBus, Display view){
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = view;
	}

	@Override
	public void bind() {
		display.getAddButton().addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				addEntry();
			}
		});

		
	}

	private void addEntry() {
		final String entryName = display.getEntryName();
		WordEntry entry = new WordEntry();
		entry.setEntryName(entryName);		
		rpcService.addWordEntry(entry, new AsyncCallback<WordEntry>() {
			
			@Override
			public void onSuccess(WordEntry result) {
				display.clearEntryName();
				display.addToList(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error adding a new word entry.");
			}
		});
	}

	@Override
	public void go(HasWidgets container) {
		bind();
		container.clear();
		container.add(display.asWidget());
		fetchWordList();
	}

	private void fetchWordList() {
		
		rpcService.searchEntries(null, new AsyncCallback<List<WordEntry>>() {
			
			@Override
			public void onSuccess(List<WordEntry> result) {
				display.setData(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error searching for Entries.");				
			}
		});
	}
	
}
